
require 'socket'

class UDPSocketManager
	def initialize(host,port)
		@host = host
		@port = port
		@punch = UDPSocket.new
		@punch.bind('', @port)
		@punch.send('', 0, @host, @port)
		@punch.close
		@udp_in = UDPSocket.new
		@udp_in.bind('0.0.0.0', @port)
	end

	def recvFrom
		# Receive data or time out
		if IO.select([@udp_in], nil, nil,0.01)
		  data = @udp_in.recvfrom(1024)
		  return data
		end
		return false
	end
	
	def send(message,host=nil,port=nil)
		if host==nil or port==nil
			@udp_in.send(message,0,@host,@port)
		else
			@udp_in.send(message,0,host,port)
		end
	end
	
	def close
		@udp_in.close
	end
end



class TCPSocketManager #just in case we may need it
	def initialize(port,host)
		@port = port
		@host = host
		@sock = TCPSocket.new(host,port)
		@data = ""
	end

	def beginRecieve(buffer)
		@t = Thread.start {
		loop do
			tempdata = @sock.recv(buffer)
			@data << tempdata
		end
		}
	end
	
	def endRecieve
		@t.join(0.5)
		data = @data
		@data = ""
		data
	end
	
	def dataSize
		@data.length
	end
	
	def send(data,async)
		if(!async)
			@sock.write(data)
		else
			Thread.start {
				@sock.write(data)
			}
		end
	end
	
	def disconnect
		@sock.close
	end
end


